package org.song.service.impl;

import cn.hutool.core.lang.Assert;
import lombok.extern.slf4j.Slf4j;
import org.song.exception.myException.CommonException;
import org.song.mapper.RoleMapper;
import org.song.mapper.UserMapper;
import org.song.mapper.UserRoleMapper;
import org.song.model.entity.RoleEntity;
import org.song.model.entity.UserRoleEntity;
import org.song.model.entity.UserEntity;
import org.song.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author song
 * @date 2022/3/10 21:17
 **/

@Slf4j
@Service( value = "roleServiceImpl")
public class RoleServiceImpl implements RoleService {

    @Autowired( required = true )
    @Qualifier( value = "userMapper")
    private UserMapper userMapper;

    @Autowired( required = true )
    @Qualifier( value = "userRoleMapper")
    private UserRoleMapper  userRoleMapper;

    @Autowired( required = true )
    @Qualifier( value = "roleMapper")
    private RoleMapper roleMapper;

    @Override
    public Set<RoleEntity> getRoleSetByUserName(String username) {
        final UserEntity userEntityByUsername = userMapper.getUserByUsername(username);
        Example userRoleExample = new Example( UserRoleEntity.class );
        userRoleExample.createCriteria().andEqualTo( "userId" , userEntityByUsername.getId() );
        final List<UserRoleEntity> userRoleEntityList = userRoleMapper.selectByExample(userRoleExample);
        Assert.isTrue( CollectionUtils.isEmpty( userRoleEntityList ) , () -> new CommonException( "当前用户未设置角色" ) );
        final Set<Long> roleIdSet = userRoleEntityList.stream().map(UserRoleEntity::getRoleId).collect(Collectors.toSet());
        final Example roleExample = new Example( RoleEntity.class );
        roleExample.createCriteria().andIn( "id" , roleIdSet );
        return new HashSet<>( roleMapper.selectByExample( roleExample ) ) ;
    }


}
